package com.ly.system.service.question.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ly.common.core.constants.Constants;
import com.ly.common.core.domain.TableDataInfo;
import com.ly.common.core.enums.ResultCode;
import com.ly.common.security.exception.ServiceException;
import com.ly.system.domain.question.Question;
import com.ly.system.domain.question.dto.QuestionAddDTO;
import com.ly.system.domain.question.dto.QuestionEditDTO;
import com.ly.system.domain.question.dto.QuestionQueryDTO;
import com.ly.system.domain.question.es.QuestionES;
import com.ly.system.domain.question.vo.QuestionDetialVO;
import com.ly.system.domain.question.vo.QuestionVO;
import com.ly.system.elasticsearch.QuestionRepository;
import com.ly.system.manager.QuestionCacheManager;
import com.ly.system.mapper.question.QuestionMapper;
import com.ly.system.service.question.IQuestionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {
        String excludeIdStr = questionQueryDTO.getExcludeIdStr();
        Set<Long> excludeIdSet = new HashSet<>(); // 默认空集合

        if (StrUtil.isNotEmpty(excludeIdStr)) {
            excludeIdSet = Arrays.stream(excludeIdStr.split(Constants.SPLIT_SEM))
                    .filter(StrUtil::isNotBlank)  // 过滤空字符串（避免 "1,,2" 的情况）
                    .map(Long::valueOf)           // 转为 Long
                    .collect(Collectors.toSet()); // 收集为 Set
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }


//       自动分页：PageHelper 会自动解析你执⾏的 SQL 语句，并根据你提供的⻚码和每页显示的记录数，
//       自动添加分页相关的 SQL ⽚段，从而返回正确的分页结果。无需在 SQL 语句中手动编写复杂的分页逻辑
        PageHelper.startPage(questionQueryDTO.getPageNum(),questionQueryDTO.getPageSize());
        return questionMapper.selectQuestionList(questionQueryDTO);

//        当前场景下的questionVOList.size()是返回当前页数下的内容
//        和total内容不一样,total返回的全部内容
//        List<QuestionVO> questionVOList =questionMapper.selectQuestionList(questionQueryDTO);
//        if (CollectionUtil.isEmpty(questionVOList)){
//            return TableDataInfo.empty();
//        }

//        //获取符合查询条件的数据总数
//        new PageInfo<>(questionVOList).getTotal();
//        return TableDataInfo.success(questionVOList,questionVOList.size());

    }

    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {
//        List<Question> questionList=questionMapper.selectList(
//                new LambdaQueryWrapper<Question>()
//                        .eq(Question::getTitle,QuestionAddDTO.getTitle()));
        List<Question> questionList = questionMapper.selectList(
                new LambdaQueryWrapper<Question>()
                        .eq(Question::getTitle, questionAddDTO.getTitle())  // 这里修正
        ); 

        if(CollectionUtil.isNotEmpty(questionList)){
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        Question question=new Question();

//        questionAddDTO：源对象（Source），通常是数据传输对象（DTO），包含前端传入的数据。
//        question：  目标对象（Target），通常是一个实体类（Entity），用于后续的数据库操作或其他业务逻辑。
//        将前端传入的 DTO 对象转换为数据库实体对象。对象属性拷贝：避免手动逐个 set 属性，简化代码。
        BeanUtils.copyProperties(questionAddDTO,question);
        int insert = questionMapper.insert(question);
        if(insert<=0){
            return false;
        }
        QuestionES questionES=new QuestionES();

        //往es中添加
        BeanUtil.copyProperties(question,questionES);
        questionRepository.save(questionES);
        questionCacheManager.addCache(question.getQuestionId());
        return true;
    }

    @Override
    public QuestionDetialVO detail(Long questionId) {
        Question question=questionMapper.selectById(questionId);

        if(question==null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        QuestionDetialVO questionDetialVO=new QuestionDetialVO();
        BeanUtils.copyProperties(question,questionDetialVO);
        return questionDetialVO;
    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        Question oldQuestion=questionMapper.selectById(questionEditDTO.getQuestionId());

        if(oldQuestion==null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }

        oldQuestion.setTitle(questionEditDTO.getTitle());
        oldQuestion.setDifficulty(questionEditDTO.getDifficulty());
        oldQuestion.setTimeLimit(questionEditDTO.getTimeLimit());
        oldQuestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        oldQuestion.setContent(questionEditDTO.getContent());
        oldQuestion.setQuestionCase(questionEditDTO.getQuestionCase());
        oldQuestion.setDefaultCode(questionEditDTO.getDefaultCode());
        oldQuestion.setMainFuc(questionEditDTO.getMainFuc());

        //在es中编辑数据(更新)
        QuestionES questionES=new QuestionES();
        BeanUtils.copyProperties(oldQuestion,questionES);
        questionRepository.save(questionES);

        return questionMapper.updateById(oldQuestion);
    }

    @Override
    public int delete(Long questionId) {
        Question Question=questionMapper.selectById(questionId);

        if(Question==null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }

        //在es中删除数据
        questionRepository.deleteById(questionId);
        questionCacheManager.deleteCache(questionId);
        return questionMapper.deleteById(questionId);

    }
}
